package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.SwitchCompat;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.UserPayment;
import com.chain.BrotherExchange.ui.adapter.TextWatcherAdapter;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.ui.window.TokenTypeWindow;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.MoneyValueFilter;
import com.chain.BrotherExchange.viewmodel.PublishTransactionOrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 发布或编辑法币交易单
 */
public class PublishTransactionOrderActivity extends BaseActivity {

    @Bind(R.id.title_bar_layout) View mTitleBarLayout;
    @Bind(R.id.more_content_layout) View mMoreContentLayout;
    @Bind(R.id.look_more_content_layout) View mLookMoreContentLayout;
    @Bind(R.id.balance_text_view) TextView balanceTextView;
    @Bind(R.id.number_text) EditText numberText;
    @Bind(R.id.lowest_price_edit) EditText lowestPriceEdit;
    @Bind(R.id.premium_text) EditText premiumText;
    @Bind(R.id.max_price_edit) EditText maxPriceEdit;
    @Bind(R.id.remark_edit) EditText remarkEdit;
    @Bind(R.id.authentication_switch) SwitchCompat authenticationSwitch;
    @Bind(R.id.more_content_hint_text) TextView mMoreContentHinText;
    @Bind(R.id.more_content_hint_image) View mMoreContentHinImage;
    @Bind(R.id.token_symbol_title_text) TextView mTokenSymbolTitleText;
    @Bind(R.id.token_symbol_text) TextView mTokenSymbolTextView;
    @Bind(R.id.token_symbol_two_text) TextView mTokenSymbolTwoTextView;
    @Bind(R.id.arrow_back_image) View mArrowBackImageView;
    @Bind(R.id.tab_layout) TabLayout mTabLayout;
    @Bind(R.id.bank_card_payment_check) CheckBox bankCardPaymentCheck;
    @Bind(R.id.ali_pay_check) CheckBox aliPayCheck;
    @Bind(R.id.we_chat_pay_check) CheckBox weChatPayCheck;
    @Bind(R.id.pay_pal_check) CheckBox payPalCheck;
    @Bind(R.id.apply_button) Button mApplyButton;
    @Bind(R.id.highest_price_edit) TextView mHighestPriceEdit;
    @Bind(R.id.unit_price_text) TextView mUnitPriceTextView;
    @Bind(R.id.bank_card_payment_layout) FrameLayout bankCardPaymentLayout;
    @Bind(R.id.ali_pay_layout) FrameLayout aliPayLayout;
    @Bind(R.id.we_chat_pay_layout) FrameLayout weChatPayLayout;
    @Bind(R.id.pay_pal_layout) FrameLayout payPalLayout;
    @Bind(R.id.free_statement_view) View mFreeStatementView;
    @Bind(R.id.total_price_text) TextView mTotalPriceTextView;

    private int tokenId, orderType = 2;
    private PublishTransactionOrderViewModel mViewModel;
    private List<String> mPaymentTypeList = new ArrayList<>();
    private UserPayment.DataBean.SetpaysBean mPayment;
    private double mUnitPriceDouble;


    public static void launch(Context context, Serializable serializable) {
        context.startActivity(new Intent(context, PublishTransactionOrderActivity.class)
                .putExtra(C.EXTRA_PAYMENT, serializable)
        );
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_issue_transaction;
    }

    @Override
    protected void initActions() {
        mViewModel = ViewModelProviders.of(this).get(PublishTransactionOrderViewModel.class);
        mPayment = (UserPayment.DataBean.SetpaysBean) getIntent()
                .getSerializableExtra(C.EXTRA_PAYMENT);

        mArrowBackImageView.setOnClickListener(v -> onBackPressed());
        mLookMoreContentLayout.setOnClickListener(v -> switchMoreContentView());

        // 免责声明
        mFreeStatementView.setOnClickListener(v -> WebViewActivity.freeStatement(this));

        // 总价
        initTotalPrice();

        // 订单货币
        initPublishOrderToken();

        // 发布订单类型
        initPublishOrderType();

        // 支付方式
        initPaymentSelector();

        // 发布订单
        mApplyButton.setOnClickListener(v -> publishOrder());

        // 百分比
        premiumText.addTextChangedListener(new TextWatcherAdapter(s -> {
            if(s != null && s.toString().length() > 0){
                try{
                    if(!"-".equals(s.toString())){
                        double percentInt = Double.parseDouble(s.toString());
                        if (percentInt <= 70 && percentInt >= -70){
                            mUnitPriceTextView.setText(new DecimalFormat("########.##")
                                    .format((percentInt / 100) * mUnitPriceDouble + mUnitPriceDouble));
                        } else {
                            s.delete(s.length() - 1, s.length());
                        }
                    }

                }catch (Exception e){
                    mUnitPriceTextView.setText(new DecimalFormat("########.########")
                            .format(mUnitPriceDouble));
                }
            } else {
                mUnitPriceTextView.setText(new DecimalFormat("########.########")
                        .format(mUnitPriceDouble));
            }
        }));
    }

    private void initTotalPrice() {
        numberText.addTextChangedListener(new TextWatcherAdapter(s -> {
            if(!TextUtils.isEmpty(s) && mUnitPriceDouble != 0){
                try {
                    double number = Double.parseDouble(s.toString());
                    mTotalPriceTextView.setText(new DecimalFormat("########.########")
                            .format(number * Double.parseDouble(mUnitPriceTextView.getText().toString())));
                } catch(Exception e){

                }
            }
        }));
    }

    private void publishOrder() {
        String tokenName = mTokenSymbolTitleText.getText().toString();
        String number = numberText.getText().toString();
        String price = mUnitPriceTextView.getText().toString();
        String lowestPrice = lowestPriceEdit.getText().toString();
        String heightPrice = mHighestPriceEdit.getText().toString();
        boolean isVerify = authenticationSwitch.isChecked();
        String premium = premiumText.getText().toString();
        String acceptPrice = maxPriceEdit.getText().toString();
        String remarkText = remarkEdit.getText().toString();

        mViewModel.publishOrder(orderType, tokenId, tokenName, price, number, premium,
                acceptPrice, lowestPrice, heightPrice, isVerify, mPaymentTypeList, remarkText)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, R.string.message_publish_trade_order_ing);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            finish();
                        }
                    }
                });
    }

    private void initPaymentSelector() {
        // 1
        bankCardPaymentLayout.setVisibility(mPayment.getBank_pay() == 0 ? View.GONE : View.VISIBLE);
        bankCardPaymentCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(1));
            } else {
                mPaymentTypeList.remove(String.valueOf(1));
            }
        });

        // 3
        aliPayLayout.setVisibility(mPayment.getAli_pay() == 0 ? View.GONE : View.VISIBLE);
        aliPayCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(3));
            } else {
                mPaymentTypeList.remove(String.valueOf(3));
            }
        });

        // 2
        weChatPayLayout.setVisibility(mPayment.getWechat_pay() == 0 ? View.GONE : View.VISIBLE);
        weChatPayCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(2));
            } else {
                mPaymentTypeList.remove(String.valueOf(2));
            }
        });

        // 4
        payPalLayout.setVisibility(mPayment.getPaypal_pay() == 0 ? View.GONE : View.VISIBLE);
        payPalCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mPaymentTypeList.add(String.valueOf(4));
            } else {
                mPaymentTypeList.remove(String.valueOf(4));
            }
        });
    }

    private void initPublishOrderToken() {
        TokenTypeWindow tokenTypeWindow = new TokenTypeWindow(this);
        mTitleBarLayout.setOnClickListener(tokenTypeWindow::show);
        tokenTypeWindow.setOnClickListener(v -> {
            String tokenSymbol = ((TextView) v).getText().toString();
            tokenId = (int) v.getTag();
            mTokenSymbolTitleText.setText(tokenSymbol);
            mTokenSymbolTextView.setText(tokenSymbol);
            mTokenSymbolTwoTextView.setText(tokenSymbol);
            loadSingleCoinBalance();
        });
    }

    private void initPublishOrderType() {
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getText().equals(getString(R.string.buy))) {
                    orderType = 1;
                } else {
                    orderType = 2;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void loadSingleCoinBalance() {
        mViewModel.singleCoinBalance(tokenId).observe(this, balance ->
                balanceTextView.setText(getString(R.string.legal_currency_account_balance) + balance.getBalance() + " ")
        );

        mViewModel.unitPrice(tokenId).observe(this, price -> {
            if (price != null) {
                mUnitPriceDouble = Double.parseDouble(price);
                mUnitPriceTextView.setText(price);
            }
        });
    }

    private void switchMoreContentView() {
        if (mMoreContentLayout.getVisibility() != View.VISIBLE) {
            mMoreContentLayout.setVisibility(View.VISIBLE);
            mMoreContentHinText.setText(R.string.collapse_more);
            mMoreContentHinImage.animate().rotation(270).start();
        } else {
            mMoreContentLayout.setVisibility(View.GONE);
            mMoreContentHinText.setText(R.string.see_more);
            mMoreContentHinImage.animate().rotation(90).start();
        }
    }
}
